package goodenglish.infrastructure.repository.db;

import goodenglish.infrastructure.TranslatorCache;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

public class TranslatorCacheDb implements TranslatorCache {
	@Override
	public void addExplain(String spell, String explain) {
		Connection conn = null;
		PreparedStatement prep = null;
		Statement stmt = null;
		try {
			conn = DBUtil.getConnection();
			stmt = conn.createStatement();
			prep = conn
					.prepareStatement("delete from  Dictionary where spell=?;");
			prep.setString(1, spell);
			prep.executeUpdate();
			prep = conn
					.prepareStatement("insert into Dictionary(spell,explain) values (?,?);");
			prep.setString(1, spell);
			prep.setString(2, explain);
			prep.executeUpdate();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			DBUtil.closeStatement(stmt, prep);
			DBUtil.closeConnection(conn);
		}

	}

	@Override
	public String getExplain(String spell) {
		Connection conn = null;
		PreparedStatement prep = null;
		try {
			conn = DBUtil.getConnection();
			prep = conn
					.prepareStatement("select explain from Dictionary where spell=?;");
			prep.setString(1, spell);
			ResultSet rs = prep.executeQuery();
			if (rs.next()) {
				return rs.getString("explain");
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			DBUtil.closeStatement(prep);
			DBUtil.closeConnection(conn);
		}
		return null;
	}

}
